package cn.itcast.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class PaiziFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }


    /**
     * 表示过滤器是否生效，false不生效，true生效
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的执行逻辑
     *
     * 没有触犯法律放行，（不需要任何额外操作，默认放行）
     * 如果触犯了，拦截，拦截的本质表现就是不响应，
     * response为空
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //如何获取request，上下文，
        RequestContext currentContext = RequestContext.getCurrentContext();

        //获取当前请求对象
        HttpServletRequest request = currentContext.getRequest();


        String paizi = request.getParameter("paizi");

        //牌子为空拦截
        if (StringUtils.isEmpty(paizi)){

            currentContext.setSendZuulResponse(false);
            //友好的返回一个状态码,未授权
            currentContext.setResponseStatusCode(401);
        }


        return null;
    }
}